<script lang="ts" setup>
import type { SystemBusinessAuditLogApi } from '#/api/per/businessAuditLog';
import type { PerBusinessMainApi } from '#/api/per/businessMain';

import { computed, defineAsyncComponent, ref, shallowRef, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { formatDateTime } from '@vben/utils';

import {
  Button,
  Card,
  Col,
  message,
  Row,
  Tag,
  Timeline,
  TimelineItem,
} from 'ant-design-vue';

import { getBusinessAuditLogList } from '#/api/per/businessAuditLog';
import { getBusinessMain } from '#/api/per/businessMain';

import AuditOpinion from './AuditOpinion.vue';

const emit = defineEmits(['success']);
// ========== 审核意见弹窗 ==========
const [AuditOpinionModal, auditOpinionModalApi] = useVbenModal({
  connectedComponent: AuditOpinion,
  destroyOnClose: true,
  zIndex: 5000,
});

// ========== 状态 ==========
const busiId = ref<string>();
const auditLogs = ref<SystemBusinessAuditLogApi.BusinessAuditLog[]>([]);
const componentPath = ref<string>('');
const DynamicDetailComponent = shallowRef<any>(null);
const editFlag = ref(false);
const loading = ref(false);
const dynamicDetailRef = ref<any>();
const height = computed(() => window.innerHeight - 350);
const showAudit = ref(false);
const operateActionMap = {
  0: { text: '提交审核', color: 'blue' },
  1: { text: '审核通过', color: 'green' },
  2: { text: '审核不通过', color: 'red' },
  3: { text: '驳回', color: 'orange' },
  4: { text: '撤销', color: 'default' },
} as const;

// ========== 主弹窗 ==========
const [Modal, modalApi] = useVbenModal({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      resetState();
      return;
    }

    const data = modalApi.getData<PerBusinessMainApi.BusinessMain>();
    if (!data?.id) return;

    busiId.value = data.id;
    showAudit.value = data.showAudit ?? false;
    modalApi.lock();
    loading.value = true;

    try {
      const businessMain = await getBusinessMain(data.id);
      componentPath.value = businessMain.component || '';

      await loadAuditLogs(data.id);
    } catch (error) {
      message.error('加载业务详情失败');
      console.error(error);
    } finally {
      modalApi.unlock();
      loading.value = false;
    }
  },
});

// ========== 函数 ==========
function resetState() {
  busiId.value = undefined;
  auditLogs.value = [];
  componentPath.value = '';
  DynamicDetailComponent.value = null;
}

async function loadAuditLogs(id: string) {
  try {
    const logs = await getBusinessAuditLogList({ businessId: id });
    auditLogs.value = Array.isArray(logs) ? logs : logs?.data || [];
  } catch {
    message.error('加载审核日志失败');
  }
}

// ========== 动态导入组件（带缓存） ==========
const componentCache = new Map<string, any>();

watch(
  componentPath,
  async (newPath) => {
    if (!newPath) return (DynamicDetailComponent.value = null);

    if (componentCache.has(newPath)) {
      DynamicDetailComponent.value = componentCache.get(newPath);
      return;
    }

    try {
      const realPath = `/src/views/${newPath}`;
      const comp = defineAsyncComponent(
        () => import(/* @vite-ignore */ realPath),
      );
      componentCache.set(newPath, comp);
      DynamicDetailComponent.value = comp;
    } catch (error) {
      console.error('组件加载失败:', error);
      message.error(`无法加载业务详情组件: ${newPath}`);
      DynamicDetailComponent.value = null;
    }
  },
  { immediate: true },
);

async function openAuditModal(finalAuditStatus: number) {
  if (!busiId.value) return;
  let modifiedData;
  // 判断是不是修改模式，如果是，把表单数据也传过去
  if (editFlag.value) {
    modifiedData = await dynamicDetailRef.value?.getFormData();
  }
  auditOpinionModalApi
    .setData({
      finalAuditStatus,
      busiId: busiId.value,
      editFlag: editFlag.value,
      modifiedData,
    })
    .open();
}

async function handleRefresh() {
  await modalApi.close();
  emit('success');
}

const toggleEdit = () => (editFlag.value = !editFlag.value);
</script>

<template>
  <AuditOpinionModal @success="handleRefresh" />

  <Modal
    title="查看业务详情"
    class="w-[85%]"
    :show-cancel-button="false"
    :show-confirm-button="false"
  >
    <Row :gutter="16">
      <!-- 左侧操作日志 -->
      <Col :span="7">
        <Card
          title="操作日志"
          :loading="loading"
          class="h-full overflow-auto"
          :style="{ maxHeight: `${height}px` }"
        >
          <Timeline>
            <TimelineItem
              v-for="(log, index) in auditLogs"
              :key="index"
              color="blue"
            >
              <div class="mb-1 font-medium">
                <Tag
                  :color="
                    operateActionMap[log.operateAction]?.color || 'default'
                  "
                >
                  {{ operateActionMap[log.operateAction]?.text || '操作' }}
                </Tag>
              </div>
              <div class="text-sm text-gray-500">
                {{ formatDateTime(log.operateTime) }}
              </div>
              <div class="mt-1 text-gray-600">
                单位：{{ log.auditorUnitName || '-' }}
              </div>
              <div class="mt-1 text-gray-600">
                操作人：{{ log.auditorName || '-' }}
              </div>
              <div class="mt-1 text-gray-600">
                意见：{{ log.auditOpinion || '无' }}
              </div>
            </TimelineItem>

            <template v-if="auditLogs.length === 0">
              <div class="mt-4 text-center text-gray-400">暂无操作日志</div>
            </template>
          </Timeline>
        </Card>
      </Col>

      <!-- 右侧详情 -->
      <Col :span="17">
        <div class="h-full overflow-auto" :style="{ maxHeight: `${height}px` }">
          <component
            v-if="DynamicDetailComponent"
            :is="DynamicDetailComponent"
            ref="dynamicDetailRef"
            :busi-id="busiId"
            :edit-flag="editFlag"
          />
          <div v-else class="p-6 text-center text-gray-400">
            暂无可用的业务详情组件
          </div>
        </div>
      </Col>
    </Row>

    <!-- 底部操作 -->
    <template #footer>
      <div class="flex flex-wrap justify-end gap-3">
        <Button v-if="showAudit" type="primary" @click="openAuditModal(1)">
          审核通过
        </Button>
        <Button v-if="!editFlag && showAudit" danger @click="openAuditModal(2)">
          审核不通过
        </Button>
        <Button v-if="!editFlag && showAudit" danger @click="openAuditModal(0)">
          驳回
        </Button>
        <Button v-if="!editFlag && showAudit" @click="toggleEdit">修改</Button>
        <Button v-if="editFlag && showAudit" @click="toggleEdit">
          取消修改
        </Button>
        <Button @click="modalApi.close()">关闭</Button>
      </div>
    </template>
  </Modal>
</template>
